import { addRoleApi, deleteRoleApi, editRoleApi } from '@/api/role/role'
import { AddRoleModel } from '@/api/role/roleModel'
import { Result } from '@/http/request'
import { EditType } from '@/type/BaseEnum'
import { ref } from 'vue'
import userInstance from '@/hooks/userInstance'

export default function tableCurd(getRoleList) {
    // 全局属性
    const {global} = userInstance()

    // 新增弹框ref属性
    const addRef = ref<{ show:(type:string,row?:AddRoleModel) => void }>()

    // 分配权限弹框ref属性
    const assignRef = ref<{ show:(id: string | number, name: string | number) => void }>()

    // 搜索
    const searchBtn = () => {
        getRoleList()
    }
    // 新增
    const addBtn = () => {
        addRef.value?.show(EditType.ADD)
    }
    // 编辑
    const editBtn = (row:AddRoleModel, test) => {
        console.log(row, test)
        addRef.value?.show(EditType.EDIT, row)
    }
    // 删除
    const deleteBtn = async (id: number) => {
        let params = {
            id: id
        }
        let confirm = await global.$myConfirm('确定删除该数据吗?')
        if(confirm) {
            let res = await deleteRoleApi(params)
             if(res && res.code === 200) {
                global.$message({
                    message: res.msg,
                    type: 'success'
                })
                getRoleList()
            }
        }
       
    }
    // 新增/编辑保存
    const save = async (params: AddRoleModel) => {
        console.log('父组件接收到参数===', params)
        let res : Result
        if(params.type === EditType.ADD) {
            res = await addRoleApi(params)

        } else {
            res = await editRoleApi(params)
        }
        if(res && res.code === 200) {
            // 刷新列表
            getRoleList()
            // 信息提示
            global.$message({
                message: res.msg,
                type: 'success'
            })
        }
    }
    // 分配权限
    const assignBtn = (id: string | number, name: string | number) => {
        assignRef.value?.show(id,name)
    }
    return {
        addRef,
        assignRef,
        searchBtn,
        addBtn,
        editBtn,
        deleteBtn,
        assignBtn,
        save
    }
}